function BidManager(){
	this.getInfoTimer = null;
	this.timer = null;
	this.timeSpan = null;
	this.datalist = null;
	this.lastReciveTime =null;
	this.firstFlush=1;
	this.updatetime = new Date().getTime();
}
$.extend(BidManager.prototype,{	
	//开始倒计时
	start : function(){
		var _this = this;	
		_this.getInfo();
	},
	stop : function(){
		var _this = this;
		this.firstFlush=1
		if(_this.getInfoTimer!=null){
			clearTimeout(_this.getInfoTimer);
		}
		if(_this.timer!=null){
			clearInterval(_this.timer);
		}		
	},	
	getInfo : function(){
		var _this = this;
		var ids=$('#ids').val();
		var _stime = new Date();
		
		if(!isEmpty(ids))
		{
			if(activetime<alerttime)
			{			
				$.ajax({url: site_root+"/auction/showauction.htm",
						data: { "gids": ids ,"f":_this.firstFlush,'t':_this.updatetime},	 
						type: "post",
						cache:false,		
						dataType: "html",
						beforeSend: function () {
							_stime = new Date();
						},
						success : function(data ){
							try {
								if(!isEmpty(data)){
									//eval('var dataobj='+data);	
									var d = eval(data);
									if(d){
										//console.log('data');
										_this.parseDataAction(d,_stime);
									}else{
										//console.log('nodata');
										$('#ids').val('');
									}									
								}
							 } catch(e){ 
								// $('#ids').val('');
								// alert("请刷新页面重试!" ); 
								// console.log('请刷新页面重试!');
							 }
						} 
				 }); 
				_this.getInfoTimer = setTimeout(function(){_this.getInfo();},1000);
			}			
		}			
	},
	parseDataAction : function(dataobj,_stime){
		_this = this;
		var obj=dataobj;
		if(!obj)return;		
		_this.datalist=obj;	
		for(i in obj){
			
			if(parseFloat($('#nowprice_'+obj[i].id).html())>0 && parseFloat(obj[i].n)-parseFloat($('#nowprice_'+obj[i].id).html())!=0)
			{
				changcolor('nowprice_'+obj[i].id);
			}
			$('#currentuser_'+obj[i].id).html(obj[i].c);
			$('#nowprice_'+obj[i].id).html(formatNum(parseFloat(obj[i].n),2));
		}	
		if(this.firstFlush){
			_this.timer = setInterval(function(){_this.refreshTimer();},50);				
			this.firstFlush=0;
		}
		_this.updatetime = obj[0].v;
		var sr = dataobj[0].rt*1;//服务器接收时间
		var ss = dataobj[0].st*1;//服务器发送时间
		if (_this.lastReciveTime==null || _this.lastReciveTime <= sr){
			var now = new Date();	              
		    _this.lastReciveTime = sr;
			_this.addStack({ serverGet: sr, serverSend: ss, sendTime: _stime, getTime: now }); 
		 }	
	},
	refreshTimer :function ()
	{
		var _this = this;
		for(i in _this.datalist){_this.timeDisplay(_this.datalist[i]);}	
	},	
	timeDisplay : function (d){	
		var _this =this;
		var id = d.id;			
		if(d.s==0 && d.m!=''){
			$('#lasttime_'+id).css('color','#ff0000');
			$('#lasttime_'+id).css('font-size','16px');
			$('#lasttime_'+id).html(d.m);
			return;
		}else if(d.s==2){
			$('#lasttime_'+id).css('background-color','#ff0000');
			$('#lasttime_'+id).css('color','#fff');
			$('#lasttime_'+id).html('竞拍成功');
			return ;
	   	}		
		var lastTime = d.l;	
		var localTime = new Date().getTime();
	    if (this.timeSpan) localTime -= this.timeSpan;
		var leftTime = lastTime-localTime;
		
		var msg = _this.getTimeDisplay(d,leftTime);
//		if(_this.lastMessage == msg)return ;
//        _this.lastMessage = msg;
		 //10以上的时候是黑色字体，9-5是红色字体，0-4是白色字体加红色背景
		if (msg!=''){
			if(leftTime <= 5000){
				$('#lasttime_'+id).css('background-color','#ff0000');
				$('#lasttime_'+id).css('color','#fff');
			}else if(leftTime < 10000){
				$('#lasttime_'+id).css('background-color','');
				$('#lasttime_'+id).css('color','#ff0000');
			}
			else{
				$('#lasttime_'+id).css('background-color','#fff');
				$('#lasttime_'+id).css('color','');
			}
			$('#lasttime_'+id).html(msg);	
		}
			
	},
	//得到商品状态显示
    getTimeDisplay: function (d,leftTime){
		var _this = this;
		var status = d.s;
		//竞拍状态 0即将竞拍1正在乐拍2竞拍成功 3小于
		var msg = "";
	   	if ( leftTime <= -3000){
		    msg = '通信中'
		 }else if(leftTime <=0 ) {
		    msg = '即将成交';
		 }else{			 
			msg = setLength(Math.floor(leftTime / 3600000), "0", 2)
		        + ":" + setLength(Math.floor(leftTime / 60000) % 60, "0", 2)
		        + ":" + setLength(Math.floor((leftTime / 1000) % 60), "0", 2);
			if (leftTime <= 1000) {
				 msg += "."+setLength(Math.floor(Math.floor(leftTime / 100) % 10), "0", 1);
			 }
		 }	
	    return msg;		
	},    //倒计时的显示
	show_alert : function()
	{
		var _this = this;
		if(activetime<alerttime)
		{
			activetime++;
			setTimeout(function(){_this.show_alert();},1000);
		}		
		else if(activetime>=alerttime)
		{
			time_wran();
			clearInterval(_this.timer);
			lock=1;
		}	
	},
	getItem : function(act,obj,page)
	{
		var _this = this;
		$.post(site_root+"/inxxx.htm?act="+act+"&cateid="+$('#cateid').val()+"&page="+page,{},
			function(data){
				var str='';
				$('#'+obj).html(data);
				$('.tempgoods').each(function(){str+=','+$(this).attr('data');});
				$('#ids').val(str.substr(1));		
				_this.stop();
				_this.start();
			});	
	},//处理服务器返回的时间验证数据
    stack: [],
    stackMaxLength: 20, //对CDN用户友好些
    addStack: function (ai) {
		var _this = this;
		_this.stack.push({
            t1: ai.sendTime.getTime() - ai.serverGet,
            t2: ai.getTime.getTime() - ai.serverSend
        });
        if (_this.stack.length > _this.stackMaxLength) _this.stack.shift();
        var tx1 = null, tx2 = null;
        for (var i = 0; i < _this.stack.length; ++i) {
            if (tx1 == null || tx1 < _this.stack[i].t1) tx1 = _this.stack[i].t1;
            if (tx2 == null || tx2 < _this.stack[i].t2) tx2 = _this.stack[i].t2;
        }
        var speed = (tx2 - tx1) / 2;
        _this.timeSpan = tx2 - speed; 
    }
	
});


//格式化字符串，把长度不满len的str使用n在前面填充到len。
function setLength(str, n, len) {
    str = str.toString();
    while (str.length < len) str = n + str.toString();
    return str;
}

function setInfo(id,uid,btn_setInfo)
{
	document.getElementById(btn_setInfo).disabled='true';
	$.ajax({url: site_root+"/auction/bid.htm",
			data: { 'aid':id,'uid':uid,'rand':Math.random() },
			type: "post",
			cache:false,
			dataType: "json",
			success : function(dataobj){
			if(dataobj.status=='success')
			{
				$('#currentuser_'+dataobj.id).html(dataobj.currentuser);
				$('#nowprice_'+dataobj.id).html(formatNum(parseFloat(dataobj.nowprice),2));
				myoldbidcount=$('#mybidcount').html();				
				if(myoldbidcount>0)
				{
					$('#mybidcount').html(myoldbidcount*1+1);
				}
				else
				{
					$('#mybidcount').html('1');
				}
				$('#myremainb').html(parseFloat($('#myremainb').html())-parseFloat($('#diffmoney').html()));
				changcolor('nowprice_'+dataobj.id);
			}
			else if(dataobj.status=='nologin')
			{
				Login_Dialog();
			}
			else if(dataobj.status=='limitnumber')
			{
				asyncbox.alert('此商品是限次竞拍,您已出价'+dataobj.number+'次');
			}
			else if(dataobj.status=='limitcount')
			{
				asyncbox.alert(dataobj.message);
			}
			
			else if(dataobj.status=='13')
			{
				asyncbox.alert('管理员已将您的id屏蔽');
			}
			else if(dataobj.status=='moneynull')
			{
				recharge_Dialog();
			}
			else if(dataobj.status=='freemoneynull')
			{
				asyncbox.alert('对不起，您的体验豆不足，验证手机后连续登录可赚取体验豆。');
			}
			else if(dataobj.status=='error')
			{
				asyncbox.alert(dataobj.message);
			}
			else if(dataobj.status=='outtime')
			{
				//$('#bidtips_'+id).html('超时');
				//$('#bidtips_'+id).show();
			}else if(dataobj.status=='2')
			{
				//varify_Dialog('setinfo');
				asyncbox.alert('您还没激活!。');
			}else{
				asyncbox.alert(dataobj.message);
			}
			setTimeout(function(){document.getElementById(btn_setInfo).disabled='';},1000);
		   }
		});
		
}

function nostart(){
	asyncbox.alert('商品未开始竞拍！');
}

//出价历史
function getBuyLog(id,dotype,logstop,ordertype)
{
	var ids=$('#ids').val();
	if(ids!='' && activetime<alerttime)
	{
		if(!dotype || dotype=='ajax'){
			$.post(site_root+"/auction/getbuylog.htm",{aid:id, datatype:'ajax',ordertype:ordertype,'rand':Math.random() },
			   function(responeData){
				if(responeData)
				{			 
				  eval('var dataobj='+responeData);			 
				  parseDataLogAction(dataobj);
				}
			   } 
			); 
		}
		else if(dotype=='iframe')
		{
			window.open(site_root+'/models/getbuylog.php?goods_id'+id+'&datatype=iframe&rand'+Math.random(),'getinfo','');
		}
		if(!logstop)
		{
			setTimeout(function(){getBuyLog(id,dotype,logstop,ordertype);},2000);
		}
	}
	
}
function parseDataLogAction(obj)
{
	for(i in obj)
	{
		$('#user_'+i).html(obj[i].name);
		$('#price_'+i).html(obj[i].bidprice);
		$('#ip_'+i).html(obj[i].ip);
		$('#salelog_'+i).show();
		$('#line_'+i).show();
	}
		
}


//我的出价信息
function getMyBuyLog(uid,pid,dotype,logstop,ordertype,showid)
{
	var ids=$('#ids').val();	
	if(ids!='' && activetime<alerttime)
	{
		if(!dotype || dotype=='ajax')
		{
			$.post(site_root+"/models/getmybuylog.php",{ goods_id:pid,uid:uid, datatype:'ajax',order:ordertype,'rand':Math.random() },
			   function(responseData){
				if(responseData)
				{				  
				  eval('var dataobj='+responseData);	
				  parseMyDataLogAction(dataobj,showid);
				}
			   } 
			); 
		}
		else if(dotype=='iframe')
		{
			window.open(site_root+'/models/getbuymylog.php?goods_id='+pid+'&datatype=iframe&rand'+Math.random(),'getinfo','');
		}
		
		if(!logstop)
		{
			setTimeout(function(){getMyBuyLog(uid,pid,dotype,logstop,ordertype,showid);},2000);
		}
	}

}
function parseMyDataLogAction(dataobj,showid)
{
	var obj=dataobj.data;
	var str='';
	for(i in obj)
	{
		if(obj[i].freemoney!=null && obj[i].freemoney>0){
			str+='<tr><td><span  target="_blank" class="blue">耗体验豆数：'+obj[i].freemoney+'粒</span></td></tr>';
		}
		
		if(obj[i].money!=null && obj[i].money>0){
			str+='<tr><td><span  target="_blank" class="blue">耗乐豆数：'+obj[i].money+'粒</span></td></tr>';
		}
		
		str+='<tr><td><span  target="_blank" class="blue">出价次数：'+obj[i].count+'次</span></td></tr>';
		if(obj[i].autocount!=null && obj[i].autocount>0){
			str+='<tr><td><span  target="_blank" class="blue">自动出价次数：'+obj[i].autocount+'次</span></td></tr>';
		}
		
		if(obj[i].money!=null && obj[i].money>0){
			if(obj[i].mode!=null && obj[i].mode==3 && obj[i].fm>0){
				str+='<tr><td><span  target="_blank" class="blue">补差价购买价格:￥'+obj[i].fm+'=￥'+obj[i].mp+'-￥'+obj[i].cm+'</span></td></tr>';
			}
			if(obj[i].mode!=null && obj[i].mode==3 && obj[i].fm<=0){
				str+='<tr><td><span  target="_blank" class="blue">补差价购买价格:￥0</span></td></tr>';
			}
		}

	}
	$('#lpk_tips').html('');
	$('#'+showid+'_'+dataobj.gid).html(str);
}



//添加聊天内容
function setChat(id,mcontent,goodsname,facenum)
{
	if(mcontent)
	{
		$.post(site_root+"/models/setchat.php",{ gid:id,content:mcontent,gname:goodsname,face:facenum,'rand':Math.random() },
			   function(data){
				if(data)
				{
				    eval('var dataobj='+data);
					if(dataobj.datastatus=='success')
					{
						if(dataobj.ispassed>0)
						{
							$('#msgerror').show()
							$('#msgerror').html('留言审核后显示');
						}
						else
						{
							$('#msgerror').show()
							if(dataobj.data[0].dmoney>0)
							{
								$("#kb_tips").animate({top:200,opacity: 'toggle'},"slow"); 
								$("#kb_tips").hide(1000); 
								$('#msgerror').html('留言成功,扣除金币'+dataobj.data[0].dmoney);
							}
							else
							{
								$('#msgerror').html('留言成功');
							}
							parseChatAction(dataobj,true);
						}
					}
					else if(dataobj.datastatus=='nomoney')
					{
						$('#msgerror').show()
						$('#msgerror').html('余额不足');
					}
					
					else if(dataobj.datastatus=='failed')
					{
						$('#msgerror').show()
						$('#msgerror').html('留言失败');
					}
					else if(dataobj.datastatus=='nologin')
					{
						$('#msgerror').show()
						$('#msgerror').html('用户未登录');
					}
					else if(dataobj.datastatus=='nouser')
					{
						$('#msgerror').show()
						$('#msgerror').html('用户不存在');
					}
				}
			   } 
			);
	}
	else
	{
		$('#msgerror').show()
		$('#msgerror').html('内容不能为空');
		
	}
	setTimeout(function(){$('#msgerror').hide();},1000);
}
//聊天内容
function getChat(id,dotype,showgoods)
{
	var ids=$('#ids').val();
	if(ids!='' && activetime<alerttime)
	{
		if(!dotype || dotype=='ajax')
		{
			$.post(site_root+"/models/getchat.php",{ gid:id, datatype:'ajax','rand':Math.random() },
			   function(data){
				if(data)
				{
				  eval('var dataobj='+data);
				  parseChatAction(dataobj,false,showgoods);
				}
			   } 
			); 
		}
		else if(dotype=='iframe')
		{
			window.open(site_root+'/models/getchat.php?gid'+id+'&datatype=iframe&rand'+Math.random(),'getinfo','');
		}
	}
	setTimeout(function(){getChat(id,dotype,showgoods);},30000);
}
function parseChatAction(dataobj,append,showgoods)
{
							
	$('#divChatList').animate({scrollTop:100000});
	var obj=dataobj.data;
	var str='';
	for(i in obj)
	{
		if(obj[i].issystem>0)
		{
			
			str+='<div id="chatitem_'+obj[i].id+'" class="chatitem chatitemsys" style="float:left;"><div class="systxt"><div style="float:left"><span class="sysname red">系统消息：</span>'+obj[i].content+'</div><div class="sysaddtime">'+obj[i].updatetime+'</div></div></div>';
		}
		else
		{
			if(showgoods)
			{
				str+='<div style="float: left;" class="chatitem" id="chatitem_'+obj[i].id+'"><div class="u"><div style="float: left;"><img src="'+uc_api+'/avatar.php?uid='+obj[i].uid+'&size=middle&type=virtual" width="13"  height="13" align="absmiddle" class="chatavatar"/><span class="username blue">'+obj[i].username+'：</span></div><div class="chatitem_emo_other"><div class="emoshape"></div><div class="emotxt">'+obj[i].content+'</div></div><div class="addtime"><span class="blue"><a href="'+site_root+'/index.php?act=goods&id='+obj[i].gid+'" target="_blank">'+obj[i].goodsname+'</a></span></div></div></div>';
			}
			else
			{
				str+='<div class="chatitem" id="chatitem_'+obj[i].id+'"><div class="u"><img height="13" width="13" align="absmiddle" class="chatavatar" src="'+uc_api+'/avatar.php?uid='+obj[i].uid+'&size=middle&type=virtual"> <span class="username blue">'+obj[i].username+'：</span></div><div class="chatitem_emo_other"><div class="emoshape"></div><div class="emotxt">'+obj[i].content+'<div class="emotime">'+obj[i].updatetime+'</div></div></div></div>';
			}
		}
	}
	if(append)
	{
		$('#divChatList').append(str);
	}
	else
	{
		$('#divChatList').html(str);
	}
	
}

function normal_time(Diffms,id,stext)
{
	var starttime=new Date(Diffms).getTime();
	var ndate=new Date().getTime();
	diff=starttime-ndate;
	if(diff>0)
	{
		var day=Math.floor(diff/(1000*60*60*24));
		var hour=Math.floor(diff/(1000*60*60))%24;
		var minute=Math.floor(diff/(1000*60))%60;
		var second=Math.floor(diff/1000)%60;
		str=hour+"小时"+minute+"分"+second+"秒";
		if(day>0)
		{
			str=day+"天"+str;
		}
		$('#'+id).html(str);
	}
	else
	{
		$('#'+id).html(stext);
	}
	

	setTimeout(function(){normal_time(Diffms,id,stext);},1000);
}
//测试速度
function testspeed()
{
	if(activetime<alerttime)
	{
		$.post(site_root+"/models/testspeed.php",{'rand':Math.random() },
			   function(data){
				data=parseInt(data);
				if(data>300 || data==0)
				{
					$('#imgSpeed').addClass('speed01');
				}
				else if(data>100 && data<300)
				{
					$('#imgSpeed').addClass('speed02');
				}
				else if(data>0 && data<100)
				{
					$('#imgSpeed').addClass('speed04');
				}
				else
				{
					$('#imgSpeed').addClass('speed00');
				}
			   } 
		);
	}
	setTimeout(function(){testspeed();},10000);
}

//微秒
var mti=8;
function domicrotime(obj)
{
	$('#lasttime_'+obj).html($('#lasttime_'+obj).html()+'.'+mti);
	if(mti>0)
	{mti--;}
	else{mti=8;}
}
//价格闪光
colori=0;
function changcolor(id){
	color=['#F60E2E','#F53752','#F46F82','#F7AAB4','#fff',''];
	$('#'+id).css('background-color',color[colori]);
	if(colori<5)
	{setTimeout(function(){changcolor(id)},50);
		colori++;}
	else{colori=0;}
}
//警告
var lock=0;

function continue_alert()
{
	activetime=1;
	lock=0;
}

document.onmousemove=function()
{
	if(lock==0)
	{
		activetime=1;
	}
}

function changexy(obj,content)
{
	pos=$(obj).offset();
	$('#p_toolTip').show();
	$('#tipcontent').html(content);
	$('#p_toolTip').css('left',pos.left*1-25+"px");
	$('#p_toolTip').css('top',pos.top*1+10+'px');
}

//add by Matthew
$(function(){
	$(".info2").hover(function(){
		$(this).addClass("hover");
	},function(){
		$(this).removeClass("hover");
	});	
});



function Map() { 
	this.elements = new Array(); 
	//获取MAP元素个数 
	this.size = function() { 
		return this.elements.length; 
	} 
	//判断MAP是否为空 
	this.isEmpty = function() { 	
		return (this.elements.length < 1); 
	} 
	//删除MAP所有元素 
	this.clear = function() { 
		this.elements = new Array(); 
	} 

	//向MAP中增加元素（key, value) 
	this.put = function(_key, _value) { 
	if(this.get(_key)){
		this.remove(_key);
	}
	this.elements.push( { 
		key : _key, 	
		value : _value 
	}); 
	} 

	//删除指定KEY的元素，成功返回True，失败返回False 
	this.remove = function(_key) { 
	var bln = false; 
	try { 
		for (i = 0; i < this.elements.length; i++) { 
			if (this.elements[i].key == _key) { 
				this.elements.splice(i, 1); 
				return true; 
			} 
		} 
		} catch (e) { 
	bln = false; 
	} 
	return bln; 
	} 

	//获取指定KEY的元素值VALUE，失败返回NULL 
	this.get = function(_key) { 
	try { 
		for (i = 0; i < this.elements.length; i++) { 
			if (this.elements[i].key == _key) { 
			return this.elements[i].value; 
			} 
		} 
	} catch (e) { 
	return null; 
	} 
	} 

	//获取指定索引的元素（使用element.key，element.value获取KEY和VALUE），失败返回NULL 
	this.element = function(_index) { 
		if (_index < 0 || _index >= this.elements.length) { 
			return null; 
		} 
		return this.elements[_index]; 
	} 

	//判断MAP中是否含有指定KEY的元素 
	this.containsKey = function(_key) { 
	var bln = false; 
	try { 
	for (i = 0; i < this.elements.length; i++) { 
		if (this.elements[i].key == _key) { 
			bln = true; 
		} 
	} 
	} catch (e) { 
	bln = false; 
	} 
	return bln; 
	} 

//判断MAP中是否含有指定VALUE的元素 
	this.containsValue = function(_value) { 
	var bln = false; 
	try { 
		for (i = 0; i < this.elements.length; i++) { 
			if (this.elements[i].value == _value) { 
				bln = true; 
			} 
		} 
	} catch (e) { 
	bln = false; 
	} 
	return bln; 
	} 

	//获取MAP中所有VALUE的数组（ARRAY） 
	this.values = function() { 
		var arr = new Array(); 
		for (i = 0; i < this.elements.length; i++) { 
			arr.push(this.elements[i].value); 
		} 
		return arr; 
	} 

	//获取MAP中所有KEY的数组（ARRAY） 
	this.keys = function() { 
		var arr = new Array(); 
		for (i = 0; i < this.elements.length; i++) { 
			arr.push(this.elements[i].key); 
		} 
	return arr; 
	} 
}

function isEmpty(str) 
{ 
	return ((typeof(str) == 'undefined' || str == null || str == "") ? true : false); 
} 
//格式化小数，并四舍五入。如：formatNum(12.345678, 4)
function formatNum(n1, n2) {
    n1 = n1.toString();
    n2 = parseInt(n2);
    var ps = n1.indexOf('.');
    if (ps == -1) {
        var k = n1 + ".";
        for (var i = 0; i < n2; ++i) k += "0";
        return k;
    }
    var vl = ps + n2 + 1;
    if (n1.length <= vl) {
        for (var i = 0; i < vl - n1.length; ++i) n1 += "0";
        return n1;
    }
    var b = n1.substring(0, vl);
    var c = n1.substring(vl, vl + 1);
    if (c == "" || parseInt(c) < 5) return b;
    return formatNum(((Math.round(parseFloat(b) * Math.pow(10, n2)) + Math.round(parseFloat(Math.pow(0.1, n2).toString().substring(0, Math.pow(0.1, n2).toString().indexOf('.') + n2 + 1)) * Math.pow(10, n2))) / Math.pow(10, n2)), n2);
}


function OnEnter(a){if(a.value==a.defaultValue){a.value=""}}
function OnExit(a){if(a.value==""){a.value=a.defaultValue}}
function OnKeyUp(a){}
function Search(key){
	if(key=='' || key=='请输入关键词'){
		alert('请输入关键词');
		return;
	}
	document.getElementById('skey').value=key;
	document.getElementById('searchform').submit();
}


